package com.example.client_group5;

import java.util.ArrayList;

import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.json.JSONArray;
import org.json.JSONObject;

import util.HttpClientFactory;

import android.os.Bundle;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TabHost.TabSpec;

public class MainActivity extends TabActivity {
	private TabHost tabHost;
	private View searchBt;
	private View tweetBt;
	private View homeBt;
	private View connectBt;
	private View discoverBt;
	private View meBt;
	private RelativeLayout layoutSearch;
	private UserSuggestAdapter adapter;
	private ArrayList<SuggestUser> list;
	private ListView listView;
	private LinearLayout mainLayout;
	private boolean isSearch = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//				WindowManager.LayoutParams.FLAG_FULLSCREEN);
//		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.activity_main);
        tabHost = getTabHost();
        TabSpec homeSpec = tabHost.newTabSpec("Home");
        homeSpec.setIndicator("", null);
        Intent homeIntent = new Intent(MainActivity.this, LazyLoading.class);
        homeSpec.setContent(homeIntent);
        
        TabSpec connectSpec = tabHost.newTabSpec("Connect");
        connectSpec.setIndicator("", null);
        Intent connectIntent = new Intent(MainActivity.this, ConnectActivity.class);
        connectSpec.setContent(connectIntent);
        
        TabSpec discoverSpec = tabHost.newTabSpec("Discover");
        discoverSpec.setIndicator("", null);
        Intent discoverIntent = new Intent(MainActivity.this, LazyLoading.class);
        discoverSpec.setContent(discoverIntent);
         



        // Adding all TabSpec to TabHost
        tabHost.addTab(homeSpec);
        tabHost.addTab(connectSpec);
        tabHost.addTab(discoverSpec);
//        tabHost.addTab(meSpec);
        mainLayout = (LinearLayout)findViewById(R.id.main_id);
        listView = (ListView)findViewById(R.id.ListViewId);
        layoutSearch = (RelativeLayout)findViewById(R.id.seach_popup_id);	
        searchBt = findViewById(R.id.btSearch);
        final EditText inputTextSearch = (EditText)findViewById(R.id.input_text_search);
        searchBt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				isSearch = true;
				layoutSearch.setVisibility(View.VISIBLE);
				Animation animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.translate);
				animation.reset();
				layoutSearch.startAnimation(animation);
				inputTextSearch.requestFocus();
				inputTextSearch.addTextChangedListener(new TextWatcher() {

					@Override
					public void onTextChanged(CharSequence arg0, int arg1,
							int arg2, int arg3) {
						// TODO Auto-generated method stub
						list = getSearch(arg0.toString());
						listView.setVisibility(View.VISIBLE);
						mainLayout.setVisibility(View.GONE);
						adapter = new UserSuggestAdapter(MainActivity.this, R.layout.list_search, list);
						listView.setAdapter(adapter);
					}

					@Override
					public void beforeTextChanged(CharSequence arg0, int arg1,
							int arg2, int arg3) {
						// TODO Auto-generated method stub

					}

					@Override
					public void afterTextChanged(Editable arg0) {
						// TODO Auto-generated method stub

					}
				});
				listView.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						if (list != null) {
							 SuggestUser user = list.get(arg2);
							 Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
							 Bundle b = new Bundle();
							 String user_id = user.user_id;
							 String username = user.username;
							 String fullname = user.fullname;
							 String avatar = user.profile_img;
							 Log.d("info", "user_id: " + user_id + " /username: " + username + " /fullname: " + fullname + " /avatar: " + avatar);
							 String[] infoProfile = {user_id, fullname, username, avatar, "home"};
							 b.putStringArray("user", infoProfile);
							 i.putExtras(b);
						     startActivity(i);
							 listView.setVisibility(View.GONE);
							 layoutSearch.setVisibility(View.GONE);
							 mainLayout.setVisibility(View.VISIBLE);
							 isSearch = false;
							 
						}
					}
				});

			}
		});

        // Tweet button action
        tweetBt = findViewById(R.id.btTweet);
        tweetBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(getApplicationContext(), TweetActivity.class);
				Bundle b = new Bundle();
				String[] replyInfo = { "tweet" };
				b.putStringArray("reply", replyInfo);
				i.putExtras(b);
				startActivity(i);
			}
		});

		// Home button action
		homeBt = findViewById(R.id.btHome);
		homeBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d("tag", "id: 1");
				setDefaultButton();
				homeBt.setBackgroundResource(R.drawable.bt_home2);
				tabHost.setCurrentTab(0);
			}
		});

        connectBt = findViewById(R.id.btConnect);
        connectBt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.d("tag", "id: 2");
				tabHost.setCurrentTab(1);
				setDefaultButton();
				connectBt.setBackgroundResource(R.drawable.bt_connect2);
			}
		});
		discoverBt = findViewById(R.id.btDiscover);
		discoverBt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.d("tag", "id: 3");
				setDefaultButton();
				discoverBt.setBackgroundResource(R.drawable.bt_discover2);
			}
		});

		meBt = findViewById(R.id.btMe);
		meBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.d("tag", "id: 4");
				setDefaultButton();
				meBt.setBackgroundResource(R.drawable.bt_me2);
				// tabHost.setCurrentTab(3);
				Intent meIntent = new Intent(MainActivity.this,
						ProfileActivity.class);
				Bundle b_me = new Bundle();
				UserManager userProfile = SignInActivity.userProfile;
				String user_id = userProfile.getUserId("userId", "");
				String fullname = userProfile.getFullName("fullname", "");
				String username = userProfile.getUserName("username", "");
				String avatar = userProfile.getAvatar("avatar", "");
				Log.d("info", "user_id: " + user_id + " /username: " + username
						+ " /fullname: " + fullname + " /avatar: " + avatar);
				String[] infoProfile = { user_id, fullname, username, avatar,
						"home" };
				b_me.putStringArray("user", infoProfile);
				meIntent.putExtras(b_me);
				startActivity(meIntent);
//				finish();
			}
		});
	}

	public void setDefaultButton() {
		homeBt.setBackgroundResource(R.drawable.bt_home1);
		connectBt.setBackgroundResource(R.drawable.bt_connect1);
		discoverBt.setBackgroundResource(R.drawable.bt_discover1);
		meBt.setBackgroundResource(R.drawable.bt_me1);
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Log.d("aaa", "isSearch:" + isSearch);
			if (isSearch) {
				isSearch = false;
				layoutSearch.setVisibility(View.GONE);
				listView.setVisibility(View.GONE);
				mainLayout.setVisibility(View.VISIBLE);
				Log.d("here", "Den day roi");
			} else {
				Log.d("dkm", "DKM");
				finish();
			}
		}
		return false;

	}
	
	public void onDestroy() {
		System.gc();
		super.onDestroy();
	}
	
	public void onResume(){
		super.onResume();
		setDefaultButton();
		homeBt.setBackgroundResource(R.drawable.bt_home2);
	}
	public ArrayList<SuggestUser> getSearch(String text) {
		String url = Setting.ipServer + "/api/user/search?k=" + text;
		ArrayList<SuggestUser> suggestList = new ArrayList<SuggestUser>();
		suggestList.add(new SuggestUser("", "", "", text));
		HttpGet get = new HttpGet(url);

		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		String responseBody = null;
		try {
			responseBody = HttpClientFactory.getThreadSafeClient().execute(get,
					responseHandler);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		Log.d("tag", "Tra ve user: " + responseBody);
		try {
			JSONArray array = new JSONArray(responseBody);
			for (int i = 0; i < array.length(); i++) {
				JSONObject t = (JSONObject) array.get(i);
				String user_id = t.getString("user_id");
				String profile_img = t.getString("avatar");
				String fullname = t.getString("fullname");
				String username = t.getString("username");
				SuggestUser user = new SuggestUser(user_id, profile_img, fullname, username);
				suggestList.add(user);
			}

		}catch(Exception e){

			e.printStackTrace();
		}

		return suggestList;
	}

	class UserSuggestAdapter extends ArrayAdapter<SuggestUser> {
		private ArrayList<SuggestUser> suggestList;
		public UserSuggestAdapter(Context context, int textViewResourceId,
				ArrayList<SuggestUser> suggestList) {
			super(context, textViewResourceId, suggestList);
			this.suggestList = suggestList;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.list_search, null);
			}
			SuggestUser user = (suggestList).get(position);
			if (user != null) {
				TextView fullname = (TextView) v.findViewById(R.id.fullname);
				TextView username = (TextView) v.findViewById(R.id.username);
				if (fullname != null) {
					fullname.setText(user.fullname);
				}
				if (username != null) {
					username.setText("@" + user.username);
				}
			}
			return v;
		}
	}
}
